package com.yingxin.yx.framework.security.handler;


import com.yingxin.yx.framework.web.ResultUtil;
import com.yingxin.yx.framework.web.resp.RespHttp;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description 登录失败处理类
 */
@Component
public class UserLoginFailureHandler implements AuthenticationFailureHandler {
    /**
     * 登录失败返回结果
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
        // 这些对于操作的处理类可以根据不同异常进行不同处理
        if (exception instanceof UsernameNotFoundException) {
            System.out.println("【登录失败】" + exception.getMessage());
            //ResultUtil.responseJson(response,ResultUtil.resultCode(500,"用户名或密码错误"));

            ResultUtil.responseJson(request, response, RespHttp.loginFail(exception.getMessage()));
            return;
        }
        if (exception instanceof BadCredentialsException) {
            System.out.println("【登录失败】" + exception.getMessage());
            //ResultUtil.responseJson(response,ResultUtil.resultCode(500,"用户名或密码错误"));

            ResultUtil.responseJson(request, response, RespHttp.loginFail(exception.getMessage()));
            return;
        }
        if (exception instanceof LockedException) {
            System.out.println("【登录失败】" + exception.getMessage());
            //ResultUtil.responseJson(response,ResultUtil.resultCode(500,"用户被冻结"));

            ResultUtil.responseJson(request, response, RespHttp.loginFail(exception.getMessage()));
            return;
        }
        if (exception instanceof DisabledException) {
            System.out.println("【登录失败】" + exception.getMessage());
            //ResultUtil.responseJson(response,ResultUtil.resultCode(500,"用户名或密码错误"));

            ResultUtil.responseJson(request, response, RespHttp.loginFail(exception.getMessage()));
            return;
        }

        //ResultUtil.responseJson(response,ResultUtil.resultCode(500,"登录失败"));

        ResultUtil.responseJson(request, response, RespHttp.loginFail("登录失败"));
    }
}